#! /usr/bin/env python
# -*- coding: utf-8 -*-

import time
import os
import re
import pycurl
import StringIO
import random

import FileHostProtoType


class fsitem(FileHostProtoType.HostItem):
    def __init__(self, name, type, code, link='', encrypt_name='', server_name=''):
        FileHostProtoType.HostItem.__init__(self, name, type, code, link, encrypt_name, server_name)
    
class freakshare(FileHostProtoType.FileHostProcess):            
    def __init__(self, user, pwd):
        FileHostProtoType.FileHostProcess.__init__(self)
        self.hostname = "FreakShare" 
        self._opener = None
        self._user = user
        self._pwd = pwd
        self.islogin = False
        self.logtype = 'poster'
        self._cookieCurl = self._user + '_freakshare.cookie'
        self._cookieCurl = os.path.join(os.path.dirname(__file__), self._cookieCurl)
            
    def login(self):        
        #try to restore cookiejar
        if self.islogin:
            return True
        self.generateOpener()
        #if self.restore_cookiejar():
        #    return True
        self.fherr.write('login to FreakShare %s/%s...' % (self._user,'*'*len(self._pwd)))
        loginData = {'user' : self._user, 
                     'pass' : self._pwd,
                     'submit' : 'Login',
                     }
        loginresult =  self.loginFileHost(
                    'http://freakshare.com/login.html', 
                    loginData
                    )
        # you always see you username at the top of the page, if login successfully.
        if self._user.lower() not in loginresult.lower():
            self.fherr.write("User %s Failed to Login MegaUpload." % self._user)
            return False
        self.fherr.write("User %s logined." % self._user)
        self.islogin = True
        return True
    
    def restore_cookiejar(self):
        '''
        load cookie file, then access website to verify if cookie is avaiable
        '''
        if os.path.isfile(self._cookieCurl):
            self.fherr.write('Restore Local Cookie.')
            try:
                self._cj.load(self._cookieCurl, ignore_discard=True)
            except:
                self.fherr.write('Failed to Restore Local CookieJar.')
            #access website to conferm cookie is avaiable
            return self.check_cookie()
        return False  

    def check_cookie(self):
        self.fherr.write('Checking Cookie...')
        response = self.post_request('http://freakshare.com/')
        if response and self._user in response:
            self.fherr.write("User %s Status : Logined." % self._user)
            self.islogin = True             
            return True
        self.fherr.write("[%s]User %s Status : not Logined." % (time.ctime(), self._user))
        self.fherr.write(response)
        return False
          
    def find(self, filenames = [], filelist = None):
        found = []
        if filelist == None:
            return found      
        filelistlower = [fl.name.lower() for fl in filelist]
        todel = []
        for fl in filenames:
            try:
                index = filelistlower.index(os.path.basename(fl).lower())
                found.append(filelist[index])
                todel.append(fl)
            except:
                continue
        for d in todel:
            filenames.remove(d)
        found.sort()
        return found
        
    def getFileList(self):
        return []
    
    def get_upload_key(self, content, key, index):
        lines = content.split('\n')
        for line in lines:
            if key in line:
                tokens = line.split('"')
                value = tokens[index]
                return value
        return ''
        
    def get_random(self):
        times = 8
        randstr = ''
        while times > 0:
            randstr += '%04x' % (random.randint(0,65534) & 0xFFFF)
            times -= 1
        return randstr
            
    def upload_web(self, file, progressLog=None, other_args=None, send_range=None):
        #indexpage
        data ={}
        indexpage = self.post_request('http://freakshare.com/').encode('utf8')
        
        keys = ['APC_UPLOAD_PROGRESS','APC_UPLOAD_USERGROUP','UPLOAD_IDENTIFIER']
        for k in keys:
            v = self.get_upload_key(indexpage, k, -2)
            data[k] = v
        
        server = self.get_upload_key(indexpage, 'return StartUpload();', 1)
        upload_link = "%s?X-Progress-ID=%s" % (server, self.get_random())
        
        filesize = os.path.getsize(file)
        filename = self.rename_func(file)
        start_point = 0
        info = "Uploading...%s" % file
        if send_range is not None:
            #range is a 3-tuple, <start, end, number>
            filesize = send_range[1] - send_range[0] + 1
            filename += ".%03d" % send_range[2]
            start_point = send_range[0]
            info += " part%d" % send_range[2]
        
        fileobj = open(file, 'rb')
        fileobj.seek(start_point) 
        data['file[1]'] = fileobj
        print data
        
        
        self.fherr.write(info)
        
        callback = None
        if progressLog is not None:
            callback = progressLog.write
        result = self.post_request(upload_link, data, cb=callback, setfilename=filename, setfilesize=filesize)
        #result
        filelink = self.get_upload_key(result, 'http://freakshare.com/files', 3)
        code = self.get_upload_key(result, 'name="file[]"', -2)
        print filelink, code
        if not code:
            self.fherr.write(result)
            self.fherr.write("Fail to upload %s" % file)
            return
        item = fsitem(os.path.basename(file), 'file', code, filelink, filename)
        self.newupload.append(item)
        self.fhout.write(item.format()) 
        return item